import React, {Component, Fragment} from 'react';
import {Link} from 'dva/router';
import {connect} from 'dva';
import {
    Row,
    Col,
    Icon,
    Card,
    Tabs,
    Table,
    Radio,
    DatePicker,
    Tooltip,
    Menu,
    Dropdown,
} from 'antd';
import numeral from 'numeral';
import {
    ChartCard,
    yuan,
    MiniArea,
    MiniBar,
    MiniProgress,
    Field,
    Bar,
    Pie,
    TimelineChart,
} from 'components/Charts';
import {
    Chart,
    Axis,
    Tooltip as ChartTooltip,
    Geom,
    Coord,
    Legend,
    Guide,
    Shape,
    Label,
    View as ChartView
} from 'bizcharts';
const {Text} = Guide;
import {Funnel} from '../../components/Charts';
import Trend from 'components/Trend';
import NumberInfo from 'components/NumberInfo';
import {getTimeDistance} from '../../utils/utils';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import {View} from '@antv/data-set';
import OrderChart from './OrderChart';


import styles from './Analysis.less';

const {TabPane} = Tabs;
const {RangePicker} = DatePicker;


const cols = {
    x: {
        range: [0, 1]
    }
}

const links = [
    {
        title: '操作一',
        href: '',
    },
    {
        title: '操作二',
        href: '',
    },
    {
        title: '操作三',
        href: '',
    },
    {
        title: '操作四',
        href: '',
    },
    {
        title: '操作五',
        href: '',
    },
    {
        title: '操作六',
        href: '',
    },
];

@connect(({dataAnalysis, orderChart, loading}) => ({
    dataAnalysis,
    orderChart,
    loading: loading.effects['dataAnalysis/fetch'],
}))
export default class Analysis extends Component {
    state = {
        salesType: 'order',
        currentTabKey: 'saleCount',
        rangePickerValue: getTimeDistance('today'),
        dateType: 0,  //0今天  1本周 2本月 3全年 4自定义时间段
    };

    componentDidMount() {
        this.props.dispatch({
            type: 'dataAnalysis/fetch',
        });
        this.props.dispatch({
            type: 'dataAnalysis/fetchFilter', //漏斗
        });
        this.props.dispatch({
            type: 'dataAnalysis/fetchGoodsPv', //商品访问排行
        });
        this.props.dispatch({
            type: 'dataAnalysis/fetchGoodsPay', //商品销量排行
        });
        this.props.dispatch({
            type: 'dataAnalysis/fetchFansChart', //粉丝拆线图
        });
    }

    componentWillUnmount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'dataAnalysis/clear',
        });
    }

    handleChangeSalesType = e => {
        this.setState({
            salesType: e.target.value,
        });
    };

    isActive(type) {
        const {rangePickerValue} = this.state;
        const value = getTimeDistance(type);
        if (!rangePickerValue[0] || !rangePickerValue[1]) {
            return;
        }
        if (
            rangePickerValue[0].isSame(value[0], 'day') &&
            rangePickerValue[1].isSame(value[1], 'day')
        ) {
            return styles.currentDate;
        }
    }

    handleRangePickerChange = rangePickerValue => {
        this.setState({
            rangePickerValue,
            dateType: 4,//时间类型 0今天  1本周 2本月 3全年 4自定义时间段
        });

        const {currentTabKey} = this.state.currentTabKey;
        this.props.dispatch({
            type: 'dataAnalysis/fetch',
            payload: {
                time_type: 4,  //时间类型 0今天  1本周 2本月 3全年 4自定义时间段
                startTime: rangePickerValue[0].format('YYYY-MM-DD'),
                endTime: rangePickerValue[1].format('YYYY-MM-DD'),
            }
        });
        this.props.dispatch({
            type: 'dashboard/fetchPvData',
            payload: {
                time_type: 4,  //时间类型 0今天  1本周 2本月 3全年 4自定义时间段
                startTime: rangePickerValue[0].format('YYYY-MM-DD'),
                endTime: rangePickerValue[1].format('YYYY-MM-DD'),
            }
        });
    };

    selectDate = type => {
        let dateType = 0;
        switch (type) {
            case 'today' :
                dateType = 0;
                break;
            case 'week' :
                dateType = 1;
                break;
            case 'month' :
                dateType = 2;
                break;
            case 'year' :
                dateType = 3;
                break;
            default :
                break;
        }
        this.setState({
            dateType: dateType,
            rangePickerValue: getTimeDistance(type),
        }, ()=> {
            const {rangePickerValue, currentTabKey} = this.state;
            this.props.dispatch({
                type: 'dataAnalysis/fetch',
                payload: {
                    time_type: dateType,  //时间类型 0今天  1本周 2本月 3全年 4自定义时间段
                    startTime: rangePickerValue[0].format('YYYY-MM-DD'),
                    endTime: rangePickerValue[1].format('YYYY-MM-DD'),
                }
            });
            this.props.dispatch({
                type: 'dashboard/fetchPvData',
                payload: {
                    time_type: dateType,  //时间类型 0今天  1本周 2本月 3全年 4自定义时间段
                    startTime: rangePickerValue[0].format('YYYY-MM-DD'),
                    endTime: rangePickerValue[1].format('YYYY-MM-DD'),
                }
            });
        });
    };

    isActive = (type)=> {
        const {rangePickerValue} = this.state;
        const value = getTimeDistance(type);
        if (!rangePickerValue[0] || !rangePickerValue[1]) {
            return;
        }
        if (
            rangePickerValue[0].isSame(value[0], 'day') &&
            rangePickerValue[1].isSame(value[1], 'day')
        ) {
            return styles.currentDate;
        }
    }

    render() {
        const {rangePickerValue, salesType, currentTabKey} = this.state;
        const {dataAnalysis, loading, orderChart} = this.props;
        const {
            visitData,
            visitData2,
            salesData,
            searchData,
            offlineData,
            offlineChartData,
            salesTypeData,
            salesTypeDataOnline,
            salesTypeDataOffline,
            filterData,
            goodsPvRank,
            goodsPayRank,
            fansChartData,
            baseData,
        } = dataAnalysis;
        const {orderData} = orderChart;


        let timeLineData = fansChartData.map(v=> {
            return {
                x: v.dateTime,
                uv: v.uv,  //访问数
                total: v.value //总数
            }
        });

        const lineDv = new View().source(timeLineData);

        lineDv.transform({
            type: 'fold',
            fields: ['uv', 'total'],
            key: 'times',
            value: 'number',
        });

        console.log('lineDv', lineDv);


        const salesExtra = (
            <div className={styles.salesExtraWrap}>
                <div className={styles.salesExtra}>
                    <a className={this.isActive('today')} onClick={() => this.selectDate('today')}>
                        今日
                    </a>
                    <a className={this.isActive('week')} onClick={() => this.selectDate('week')}>
                        本周
                    </a>
                    <a className={this.isActive('month')} onClick={() => this.selectDate('month')}>
                        本月
                    </a>
                    <a className={this.isActive('year')} onClick={() => this.selectDate('year')}>
                        全年
                    </a>
                </div>
                <RangePicker
                    value={rangePickerValue}
                    onChange={this.handleRangePickerChange}
                    style={{width: 256}}
                />
            </div>
        );

        const topColResponsiveProps = {
            xs: 24,
            sm: 12,
            md: 12,
            lg: 12,
            xl: 6,
            style: {marginBottom: 24},
        };

        let filterList = filterData.map(v=> {
            return {
                action: v.key,
                pv: v.value,
            }
        });
        const dv = new View().source(filterList);

        dv.transform({
            type: 'percent',
            field: 'pv',
            dimension: 'action',
            as: 'percent'
        });
        filterList = dv.rows;

        console.log('filterList', filterList);

        return (
            <Fragment>
                <PageHeaderLayout
                    title="数据概况"
                    content={
                        <div style={{'float': 'right'}}>{salesExtra}</div>
                    }
                ></PageHeaderLayout>
                <Row gutter={24} style={{marginTop: '24px'}}>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="商城访客数"
                            action={
                                <Tooltip title="商城UV">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={baseData.uv || 0}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="下单人数"
                            action={
                                <Tooltip title="包含未支付的人数">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={baseData.order_user_count || 0}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="下单笔数"
                            action={
                                <Tooltip title="包含未支持订单">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={baseData.order_total || 0}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="下单金额"
                            action={
                                <Tooltip title="包含未支持金额">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={'¥' + (baseData.order_price_total || 0)}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="付款人数"
                            action={
                                <Tooltip title="已支付人员数量">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={baseData.order_pay_user_count || 0}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="付款订单数"
                            action={
                                <Tooltip title="已支付订单数量">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={baseData.order_pay_total || 0}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="付款金额"
                            action={
                                <Tooltip title="已支付订单金额">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={'¥' + (baseData.order_pay_price_total || 0)}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="付款件数"
                            action={
                                <Tooltip title="已支付订单商品数量">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={baseData.pay_order_goods_count || 0}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="访客下单转化率"
                            action={
                                <Tooltip title="订单数/uv">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={`${baseData.uv_order_rate || 0}%`}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="访客付款转化率"
                            action={
                                <Tooltip title="访客数量/付款数量">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={`${baseData.uv_pay_order_rate || 0}%`}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="下单付款转化率"
                            action={
                                <Tooltip title="下单数量/已支付订单数">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={`${baseData.order_pay_rate || 0}%`}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                    <Col {...topColResponsiveProps}>
                        <ChartCard
                            bordered={true}
                            title="客单价"
                            action={
                                <Tooltip title="订单价格/订单数量">
                                    <Icon type="info-circle-o"/>
                                </Tooltip>
                            }
                            total={`¥${baseData.per_c_p || 0}`}
                            contentHeight={46}
                        >
                        </ChartCard>
                    </Col>
                </Row>
                <Card loading={loading} bordered={false} bodyStyle={{padding: 0}}>
                    <div className={styles.salesCard}>
                        <OrderChart dispatch={ this.props.dispatch} data={orderData} type={['order', 'sales']}/>
                    </div>
                </Card>
                <Row gutter={24} style={{'marginTop': '24px'}}>
                    <Col xs={24}>
                        <Card
                            title=""
                            bordered={false}
                            bodyStyle={{padding: 0}}
                            style={{height: '594px'}}
                        >
                            {filterList.length > 0 ?
                                <Chart height={500} data={filterList} scale={cols} padding={[20, 120, 95]} forceFit>
                                    <ChartTooltip showTitle={false}
                                                  itemTpl='<li data-index={index} style="margin-bottom:4px;"><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}<br/><span style="padding-left: 16px">次数：{pv}</span><br/><span style="padding-left: 16px">占比：{percent}</span><br/></li>'/>
                                    <Coord type='rect' transpose scale={[1, -1]}/>
                                    <Legend />
                                    <Guide >
                                        {filterList.map((obj, i) => {
                                            return (
                                                <Text
                                                    key={i}
                                                    top={true}
                                                    position={{
                                                        action: obj.action,
                                                        percent: 'median'
                                                    }}
                                                    content={parseInt(obj.percent * 100) + '%'}
                                                    style={{
                                                        fill: '#fff',
                                                        fontSize: '12',
                                                        textAlign: 'center',
                                                        shadowBlur: 2,
                                                        shadowColor: 'rgba(0, 0, 0, .45)'
                                                    }}
                                                />
                                            )
                                        })}
                                    </Guide>
                                    <Geom type="intervalSymmetric" position="action*percent" shape='funnel'
                                          color={['action', ['#0050B3', '#1890FF', '#40A9FF', '#69C0FF', '#BAE7FF']]}
                                          tooltip={['action*pv*percent', (action, pv, percent) => {
                                              return {
                                                  name: action,
                                                  percent: parseInt(percent * 100) + '%',
                                                  pv: pv
                                              };
                                          }]}
                                    >
                                        <Label content={['action*pv', (action, pv) => {
                                            return action + ' ' + pv;
                                        }]}
                                               offset={35}
                                               labeLine={{
                                                   lineWidth: 1,
                                                   stroke: 'rgba(0, 0, 0, 0.15)'
                                               }}
                                        />
                                    </Geom>
                                </Chart>
                                : null
                            }

                        </Card>
                    </Col>
                </Row>
                <Row gutter={24}>
                    <Col xs={12}>
                        <Card
                            title="商品访问排行"
                            bordered={false}
                            bodyStyle={{padding: '0 24px 24px'}}
                            style={{marginTop: '24px'}}
                        >
                            <ul className={styles.rankingList} style={{height: '364px'}}>
                                {goodsPvRank.map((item, i) => (
                                    <li key={'pv' + item.goods_id}>
                                        <span className={i < 3 ? styles.active : ''}>{i + 1}</span>
                                        <span><a href="javascript:;"> {item.goods_name}</a></span>
                                        <span><Tooltip title="访问数/销售数">{item.pv}/{item.sale_count}</Tooltip></span>
                                    </li>
                                ))}
                            </ul>
                        </Card>
                    </Col>
                    <Col xs={12}>
                        <Card
                            title="商品支付排行"
                            bordered={false}
                            bodyStyle={{padding: '0 24px 24px'}}
                            style={{marginTop: '24px'}}
                        >
                            <ul className={styles.rankingList} style={{height: '364px'}}>
                                {goodsPayRank.map((item, i) => (
                                    <li key={'pay' + item.goods_name}>
                                        <span className={i < 3 ? styles.active : ''}>{i + 1}</span>
                                        <span><a href="javascript:;">{item.goods_name}</a></span>
                                        <span>{numeral(item.value).format('0,0')}</span>
                                    </li>
                                ))}
                            </ul>
                        </Card>
                    </Col>
                </Row>
                <Card
                    title="粉丝变化趋势图"
                    bordered={false}
                    style={{marginTop: '24px'}}
                >
                    <div style={{margin: '0 auto', 'width': '876px'}}>
                        <Chart padding={[30, 20, 80, 40]} width={876} height={400} data={lineDv}>
                            <Legend />
                            <ChartTooltip crosshairs={{type: "y"}}/>
                            <Axis name="x" subTickCount={2}/>
                            <Axis name="total" label={{formatter: val => `${val}`}}/>
                            <Geom type="line" position="x*number" size={2} color={'times'} shape={'smooth'}/>
                            <Geom type='point' position="x*number" size={4} shape={'circle'} color={'times'}
                                  style={{stroke: '#fff', lineWidth: 1}}/>
                        </Chart>
                    </div>
                </Card>
            </Fragment>
        );
    }
}
